package com.mfw.springboot.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mfw.springboot.annotation.AuthCheck;
import com.mfw.springboot.common.*;
import com.mfw.springboot.constant.UserConstant;
import com.mfw.springboot.exception.BusinessException;
import com.mfw.springboot.exception.ThrowUtils;
import com.mfw.springboot.model.dto.trainingRule.*;
import com.mfw.springboot.model.entity.TrainingRule;
import com.mfw.springboot.model.entity.User;
import com.mfw.springboot.model.vo.TrainingRuleVO;
import com.mfw.springboot.service.TrainingRuleService;
import com.mfw.springboot.service.UserService;
import com.mfw.springboot.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 训练规则接口
 *
 * @author mfw
 * @from <a href="https://gitee.com/hanhuaifei/projects">我的gitee</a>
 * @Date 2024/9/26
 */
@RestController
@RequestMapping("/trainingRule")
@Slf4j
public class TrainingRuleController {

    @Resource
    private TrainingRuleService trainingRuleService;

    @Resource
    private UserService userService;


    /**
     * 根据ids获取训练规则列表（封装类）
     *
     * @param trainingRuleIdListRequest
     * @param request
     * @return
     */
    @PostMapping("/list/ids/vo")
    public BaseResponse<List<TrainingRuleVO>> listTrainingRuleVOByIds(@RequestBody TrainingRuleIdListRequest trainingRuleIdListRequest, HttpServletRequest request) {

        ThrowUtils.throwIf(trainingRuleIdListRequest == null, ErrorCode.PARAMS_ERROR);

        List<Integer> ids = trainingRuleIdListRequest.getIds();

        // 查询数据库
        List<TrainingRule> trainingRuleList = trainingRuleService.listByIds(ids);
        // 获取封装类
        List<TrainingRuleVO> trainingRuleVOList = trainingRuleList
                .stream()
                .map(trainingRule -> trainingRuleService.getTrainingRuleVO(trainingRule, request))
                .collect(Collectors.toList());
        //返回
        return Result.success(trainingRuleVOList);
    }


    // region 增删改查

    /**
     * 创建训练规则
     *
     * @param trainingRuleAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addTrainingRule(@RequestBody TrainingRuleAddRequest trainingRuleAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(trainingRuleAddRequest == null, ErrorCode.PARAMS_ERROR);
        // 在此处将实体类和 DTO 进行转换
        TrainingRule trainingRule = new TrainingRule();
        BeanUtils.copyProperties(trainingRuleAddRequest, trainingRule);
        // 数据校验
        trainingRuleService.validTrainingRule(trainingRule, true);
        // 填充默认值
        User loginUser = userService.getLoginUser(request);
        trainingRule.setUserId(loginUser.getId());
        // 写入数据库
        boolean result = trainingRuleService.save(trainingRule);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newTrainingRuleId = trainingRule.getId();
        return Result.success(newTrainingRuleId);
    }

    /**
     * 删除训练规则
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteTrainingRule(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        TrainingRule oldTrainingRule = trainingRuleService.getById(id);
        ThrowUtils.throwIf(oldTrainingRule == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldTrainingRule.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = trainingRuleService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return Result.success(true);
    }

    /**
     * 更新训练规则（仅管理员可用）
     *
     * @param trainingRuleUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateTrainingRule(@RequestBody TrainingRuleUpdateRequest trainingRuleUpdateRequest) {
        if (trainingRuleUpdateRequest == null || trainingRuleUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 在此处将实体类和 DTO 进行转换
        TrainingRule trainingRule = new TrainingRule();
        BeanUtils.copyProperties(trainingRuleUpdateRequest, trainingRule);
        // 数据校验
        trainingRuleService.validTrainingRule(trainingRule, false);
        // 判断是否存在
        long id = trainingRuleUpdateRequest.getId();
        TrainingRule oldTrainingRule = trainingRuleService.getById(id);
        ThrowUtils.throwIf(oldTrainingRule == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = trainingRuleService.updateById(trainingRule);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return Result.success(true);
    }

    /**
     * 根据 id 获取训练规则（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<TrainingRuleVO> getTrainingRuleVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        TrainingRule trainingRule = trainingRuleService.getById(id);
        ThrowUtils.throwIf(trainingRule == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return Result.success(trainingRuleService.getTrainingRuleVO(trainingRule, request));
    }

    /**
     * 分页获取训练规则列表（仅管理员可用）
     *
     * @param trainingRuleQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<TrainingRule>> listTrainingRuleByPage(@RequestBody TrainingRuleQueryRequest trainingRuleQueryRequest) {
        long current = trainingRuleQueryRequest.getCurrent();
        long size = trainingRuleQueryRequest.getPageSize();
        // 查询数据库
        Page<TrainingRule> trainingRulePage = trainingRuleService.page(new Page<>(current, size),
                trainingRuleService.getQueryWrapper(trainingRuleQueryRequest));
        return Result.success(trainingRulePage);
    }

    /**
     * 分页获取训练规则列表（封装类）
     *
     * @param trainingRuleQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<TrainingRuleVO>> listTrainingRuleVOByPage(@RequestBody TrainingRuleQueryRequest trainingRuleQueryRequest,
                                                                       HttpServletRequest request) {
        long current = trainingRuleQueryRequest.getCurrent();
        long size = trainingRuleQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<TrainingRule> trainingRulePage = trainingRuleService.page(new Page<>(current, size),
                trainingRuleService.getQueryWrapper(trainingRuleQueryRequest));
        // 获取封装类
        return Result.success(trainingRuleService.getTrainingRuleVOPage(trainingRulePage, request));
    }

    /**
     * 分页获取当前登录用户创建的训练规则列表
     *
     * @param trainingRuleQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<TrainingRuleVO>> listMyTrainingRuleVOByPage(@RequestBody TrainingRuleQueryRequest trainingRuleQueryRequest,
                                                                         HttpServletRequest request) {
        ThrowUtils.throwIf(trainingRuleQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        trainingRuleQueryRequest.setUserId(loginUser.getId());
        long current = trainingRuleQueryRequest.getCurrent();
        long size = trainingRuleQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<TrainingRule> trainingRulePage = trainingRuleService.page(new Page<>(current, size),
                trainingRuleService.getQueryWrapper(trainingRuleQueryRequest));
        // 获取封装类
        return Result.success(trainingRuleService.getTrainingRuleVOPage(trainingRulePage, request));
    }

    /**
     * 编辑训练规则（给用户使用）
     *
     * @param trainingRuleEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editTrainingRule(@RequestBody TrainingRuleEditRequest trainingRuleEditRequest, HttpServletRequest request) {
        if (trainingRuleEditRequest == null || trainingRuleEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 在此处将实体类和 DTO 进行转换
        TrainingRule trainingRule = new TrainingRule();
        BeanUtils.copyProperties(trainingRuleEditRequest, trainingRule);
        // 数据校验
        trainingRuleService.validTrainingRule(trainingRule, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = trainingRuleEditRequest.getId();
        TrainingRule oldTrainingRule = trainingRuleService.getById(id);
        ThrowUtils.throwIf(oldTrainingRule == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldTrainingRule.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = trainingRuleService.updateById(trainingRule);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return Result.success(true);
    }

    /**
     * 日新增统计训练规则
     *
     * @return
     */
    @PostMapping("/day/newly/added")
    public BaseResponse<List<DataGroupByDateDTO>> dayNewlyAddedTrainingRule() {
        // 今天
        Date endDate = DateUtils.getNow();
        // 30天以前
        Date beginDate = DateUtils.dayAfter(endDate, -30);
        // 查询
        List<DataGroupByDateDTO> trainingRuleDataList = trainingRuleService.countByDay(beginDate, endDate);
        //返回结果
        return Result.success(trainingRuleDataList);

    }

    // endregion
}
